package com.wn.icloud.service.impl;

import com.wn.icloud.dao.BaseTreeDao;
import com.wn.icloud.domain.BaseTreeEntityDomain;
import com.wn.icloud.service.BaseTreeService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liguangcai
 * @date 2018/11/30 20:09
 */
@Transactional
public class BaseTreeServiceImpl<T extends BaseTreeEntityDomain<T>, ID extends Serializable, TreeDao extends BaseTreeDao<T, ID>> extends BaseServiceImpl<T, ID, TreeDao> implements BaseTreeService<T, ID> {

//	protected BaseTreeDao<T, ID> treeDao;

    @Autowired
    public TreeDao treeDao;

    @Override
    public List<T> getRoot() {
        return this.treeDao.getRoot();
    }

    @Override
    public List<T> getChildren(ID id) {
        T entity = this.treeDao.getOne(id);
        return entity.getChildren();
    }

    @Override
    public List<T> getDescendants(ID id) {
        List<T> descendants = new ArrayList<T>();
        List<T> children = this.getChildren(id);
        if (children != null && children.size() > 0) { // 追加子孙
            descendants.addAll(children);
            for (T t : children) {
                @SuppressWarnings("unchecked")
                List<T> descendants2 = this.getDescendants((ID) t.getId());
                descendants.addAll(descendants2);
            }
        }
        return descendants;
    }

    @Override
    public List<T> getAncestors(ID id) {
        List<T> ancestors = new ArrayList<T>();
        T entity = this.treeDao.getOne(id);
        T parent = entity.getParent();
        while (parent != null) { // 追述祖先
            ancestors.add(parent);
            entity = parent;
            parent = entity.getParent();
        }
        return ancestors;
    }

}
